// UserProgressService.java
package com.example.gymlearning.service;

import com.example.gymlearning.entity.UserPointProgress;
import com.example.gymlearning.entity.UserPackageProgress;
import com.example.gymlearning.mapper.UserProgressMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserProgressService {

    private final UserProgressMapper userProgressMapper;
    private final KnowledgePointService knowledgePointService;
    private final KnowledgePackageService knowledgePackageService;

    /**
     * 初始化用户知识点进度
     */
    public void initUserPointProgress(Long userId, Long pointId) {
        UserPointProgress progress = userProgressMapper.findPointProgress(userId, pointId);
        if (progress == null) {
            progress = new UserPointProgress();
            progress.setUserId(userId);
            progress.setPointId(pointId);
            progress.setStatus("NOT_STARTED");
            progress.setAttemptCount(0);
            progress.setLearningCount(0);
            progress.setTotalDurationSeconds(0);
            progress.setCreatedTime(new Date());
            userProgressMapper.insertPointProgress(progress);
            log.info("初始化用户知识点进度: userId={}, pointId={}", userId, pointId);
        }
    }

    /**
     * 更新知识点进度为进行中
     */
    public void startPointProgress(Long userId, Long pointId) {
        UserPointProgress progress = userProgressMapper.findPointProgress(userId, pointId);
        if (progress != null) {
            progress.setStatus("IN_PROGRESS");
            progress.setStartTime(new Date());
            progress.setUpdatedTime(new Date());
            userProgressMapper.updatePointProgress(progress);
        }
    }

    /**
     * 完成知识点学习
     */
    @Transactional
    public void completePointProgress(Long userId, Long pointId, Integer score) {
        try {
            // 更新知识点进度
            UserPointProgress progress = userProgressMapper.findPointProgress(userId, pointId);
            if (progress != null) {
                progress.setStatus("COMPLETED");
                progress.setBestScore(score);
                progress.setCompleteTime(new Date());
                progress.setUpdatedTime(new Date());
                progress.setAttemptCount(progress.getAttemptCount() + 1);
                userProgressMapper.updatePointProgress(progress);
            }

            // 更新知识包进度
            updatePackageProgress(userId, pointId);

            log.info("完成知识点学习: userId={}, pointId={}, score={}", userId, pointId, score);
        } catch (Exception e) {
            log.error("完成知识点进度失败: {}", e.getMessage(), e);
            throw new RuntimeException("更新学习进度失败");
        }
    }

    /**
     * 更新知识包进度
     */
    private void updatePackageProgress(Long userId, Long pointId) {
        try {
            // 获取知识点所属的知识包
            Long packageId = knowledgePointService.getPackageIdByPointId(pointId);
            if (packageId == null) return;

            // 获取或创建知识包进度
            UserPackageProgress packageProgress = userProgressMapper.findPackageProgress(userId, packageId);
            if (packageProgress == null) {
                packageProgress = new UserPackageProgress();
                packageProgress.setUserId(userId);
                packageProgress.setPackageId(packageId);
                packageProgress.setStatus("IN_PROGRESS");
                packageProgress.setGatewayUnlocked(false);
                packageProgress.setGatewayCompleted(false);
                packageProgress.setCreatedTime(new Date());

                // 设置知识点统计
                int totalPoints = knowledgePointService.getPointCountByPackage(packageId);
                packageProgress.setTotalPoints(totalPoints);
                packageProgress.setCompletedPoints(0);

                userProgressMapper.insertPackageProgress(packageProgress);
            }

            // 更新完成的知识点数量
            int completedCount = userProgressMapper.getCompletedPointsCount(userId, packageId);
            packageProgress.setCompletedPoints(completedCount);
            packageProgress.setUpdatedTime(new Date());

            // 检查是否完成所有知识点，解锁知识包闯关
            if (completedCount >= packageProgress.getTotalPoints()) {
                packageProgress.setGatewayUnlocked(true);
                packageProgress.setStatus("READY_FOR_GATEWAY");
                log.info("解锁知识包闯关: userId={}, packageId={}", userId, packageId);
            }

            userProgressMapper.updatePackageProgress(packageProgress);

        } catch (Exception e) {
            log.error("更新知识包进度失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 解锁知识包闯关
     */
    public void unlockPackageGateway(Long userId, Long packageId) {
        UserPackageProgress progress = userProgressMapper.findPackageProgress(userId, packageId);
        if (progress != null) {
            progress.setGatewayUnlocked(true);
            progress.setUpdatedTime(new Date());
            userProgressMapper.updatePackageProgress(progress);
            log.info("解锁知识包闯关: userId={}, packageId={}", userId, packageId);
        }
    }

    /**
     * 完成知识包闯关
     */
    @Transactional
    public void completePackageGateway(Long userId, Long packageId, Integer score, Integer correctAnswers, Integer totalQuestions) {
        try {
            UserPackageProgress progress = userProgressMapper.findPackageProgress(userId, packageId);
            if (progress != null) {
                progress.setGatewayCompleted(true);
                progress.setGatewayScore(score);
                progress.setStatus("COMPLETED");
                progress.setGatewayCompleteTime(new Date());
                progress.setUpdatedTime(new Date());
                userProgressMapper.updatePackageProgress(progress);
            }

            // 解锁下一个知识包
            unlockNextPackage(userId, packageId);

            log.info("完成知识包闯关: userId={}, packageId={}, score={}", userId, packageId, score);
        } catch (Exception e) {
            log.error("完成知识包闯关失败: {}", e.getMessage(), e);
            throw new RuntimeException("更新知识包进度失败");
        }
    }

    /**
     * 解锁下一个知识包
     */
    private void unlockNextPackage(Long userId, Long currentPackageId) {
        try {
            Long nextPackageId = knowledgePackageService.getNextPackageId(currentPackageId);
            if (nextPackageId != null) {
                // 初始化下一个知识包的进度
                UserPackageProgress nextProgress = userProgressMapper.findPackageProgress(userId, nextPackageId);
                if (nextProgress == null) {
                    nextProgress = new UserPackageProgress();
                    nextProgress.setUserId(userId);
                    nextProgress.setPackageId(nextPackageId);
                    nextProgress.setStatus("NOT_STARTED");
                    nextProgress.setGatewayUnlocked(false);
                    nextProgress.setGatewayCompleted(false);

                    int totalPoints = knowledgePointService.getPointCountByPackage(nextPackageId);
                    nextProgress.setTotalPoints(totalPoints);
                    nextProgress.setCompletedPoints(0);
                    nextProgress.setCreatedTime(new Date());

                    userProgressMapper.insertPackageProgress(nextProgress);
                    log.info("解锁下一个知识包: userId={}, packageId={}", userId, nextPackageId);
                }
            }
        } catch (Exception e) {
            log.error("解锁下一个知识包失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 获取用户的知识包进度
     */
    public UserPackageProgress getPackageProgress(Long userId, Long packageId) {
        return userProgressMapper.findPackageProgress(userId, packageId);
    }

    /**
     * 检查知识包闯关是否解锁
     */
    public boolean isPackageGatewayUnlocked(Long userId, Long packageId) {
        UserPackageProgress progress = userProgressMapper.findPackageProgress(userId, packageId);
        return progress != null && Boolean.TRUE.equals(progress.getGatewayUnlocked());
    }

    /**
     * 记录知识点学习次数与总时长
     */
    public void addLearningDuration(Long userId, Long pointId, Integer durationSeconds) {
        if (userId == null || pointId == null || durationSeconds == null) {
            return;
        }
        UserPointProgress progress = userProgressMapper.findPointProgress(userId, pointId);
        if (progress == null) {
            initUserPointProgress(userId, pointId);
            progress = userProgressMapper.findPointProgress(userId, pointId);
        }
        if (progress == null) {
            return;
        }
        if (progress.getStatus() == null || "NOT_STARTED".equalsIgnoreCase(progress.getStatus())) {
            progress.setStatus("IN_PROGRESS");
            progress.setStartTime(progress.getStartTime() == null ? new Date() : progress.getStartTime());
        }
        if (progress.getLearningCount() == null) {
            progress.setLearningCount(0);
        }
        if (progress.getTotalDurationSeconds() == null) {
            progress.setTotalDurationSeconds(0);
        }
        progress.setLearningCount(progress.getLearningCount() + 1);
        progress.setTotalDurationSeconds(progress.getTotalDurationSeconds() + durationSeconds);
        progress.setUpdatedTime(new Date());
        userProgressMapper.updatePointProgress(progress);
    }

    public UserPointProgress getPointProgress(Long userId, Long pointId) {
        if (userId == null || pointId == null) {
            return null;
        }
        return userProgressMapper.findPointProgress(userId, pointId);
    }

    public int getPointDurationSeconds(Long userId, Long pointId) {
        if (userId == null || pointId == null) {
            return 0;
        }
        Integer seconds = userProgressMapper.getPointDurationSeconds(userId, pointId);
        return seconds == null ? 0 : seconds;
    }

    public int getPackageDurationSeconds(Long userId, Long packageId) {
        if (userId == null || packageId == null) {
            return 0;
        }
        Integer seconds = userProgressMapper.getPackageDurationSeconds(userId, packageId);
        return seconds == null ? 0 : seconds;
    }

    public int getModuleDurationSeconds(Long userId, Long moduleId) {
        if (userId == null || moduleId == null) {
            return 0;
        }
        Integer seconds = userProgressMapper.getModuleDurationSeconds(userId, moduleId);
        return seconds == null ? 0 : seconds;
    }

    public int getClassDurationSeconds(Long userId, Long classId) {
        if (userId == null || classId == null) {
            return 0;
        }
        Integer seconds = userProgressMapper.getClassDurationSeconds(userId, classId);
        return seconds == null ? 0 : seconds;
    }

}